package com.company.emallbackend.service.impl;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.emallbackend.entity.Product;
import com.company.emallbackend.exception.CommonException;
import com.company.emallbackend.mapper.ProductMapper;
import com.company.emallbackend.service.IProductService;
import com.company.emallbackend.utils.ConstantPropertiesUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hanlijian
 * @since 2023-01-12
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Override
    public String upload(MultipartFile file) {
        if(Objects.isNull(file)){
            throw new CommonException(201,"您上传的文件错误");
        }
        //获取阿里云常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String url= null;
        try {
            //创建Oss实例
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            //获取文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();
            //在文件名中添加随机值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName=uuid+fileName;
            //把文件按照日期分类
            String dataPath=new DateTime().toString("yyyy/MM/dd");
            //拼接
            fileName=dataPath+"/"+fileName;
            //调用oss方法实现上传
            //第一个参数 Bucket名称
            //第二个参数 上传到oss文件路径和文件名称
            //第三个参数 上传文件输入流
            ossClient.putObject(bucketName,fileName,inputStream);
            //管理oss连接
            ossClient.shutdown();
            //把上传之后文件路径返回
            //需要把文件上传到阿里云oss路径手动拼接出来
            //https://edu-hlj.oss-cn-beijing.aliyuncs.com/02.jpg
            url = "https://"+bucketName+"."+endPoint+"/"+fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }
}
